<template>
  <div class="app-container">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="140px" :label-position="isPhone ? 'top' : 'left'">
      <el-row>
        <el-col :span="24">
          <el-form-item label="学生" prop="userId">
            <el-select
              v-model="form.userId"
              placeholder="请选择学生"
              clearable
              style="width: 100%"
              :disabled="pageMode === 'detail' || pageMode === 'approve'"
              @change="handleStudentChange"
            >
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="高校导师" prop="schoolTeacherUserId">
            <el-select
              v-model="form.schoolTeacherUserId"
              placeholder="请选择高校导师"
              clearable
              style="width: 100%"
              :disabled="pageMode === 'detail' || pageMode === 'approve'"
              @change="handleSchoolTeacherChange"
            >
              <el-option
                v-for="item in schoolTeacherUserList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="selectedSchoolTeacher">
          <el-form-item label="单位">
            <el-input
              v-model="selectedSchoolTeacher.deptName"
              disabled
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="selectedSchoolTeacher">
          <el-form-item label="职务">
            <el-input
              v-model="selectedSchoolTeacher.position"
              disabled
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="selectedSchoolTeacher">
          <el-form-item label="职称">
            <el-input
              :value="selectDictLabel(professional_title, selectedSchoolTeacher.rank)"
              disabled
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="selectedSchoolTeacher">
          <el-form-item label="学历">
            <el-input
              :value="selectDictLabel(educational_qualifications, selectedSchoolTeacher.qualification)"
              disabled
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="selectedSchoolTeacher">
          <el-form-item label="联系电话">
            <el-input
              v-model="selectedSchoolTeacher.phonenumber"
              disabled
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 审批进度组件 -->
      <el-row v-if="form.approvalInfoId">
        <el-col :span="24">
          <approval-progress :approval-info-id="form.approvalInfoId" />
        </el-col>
      </el-row>
      
      <el-form-item
        label="审核意见"
        prop="approvalRemark"
        v-if="form.approvalStatus === 'rejected'"
      >
        <el-input
          v-model="form.approvalRemark"
          disabled
          type="textarea"
          placeholder="请输入审核意见"
          :rows="3"
          style="width: 100%"
        ></el-input>
      </el-form-item>
      <!-- 审批模式下的审核意见字段 -->
      <div v-if="pageMode === 'approve'" style="margin-top: 20px">
        <el-form-item
          label="审核意见"
          prop="approvalRemark"
        >
          <el-input
            v-model="form.approvalRemark"
            type="textarea"
            placeholder="请输入审核意见"
            :rows="3"
            style="width: 100%"
          ></el-input>
        </el-form-item>
      </div>
    </el-form>

    <div class="dialog-footer" style="text-align: right; margin-top: 20px">
      <!-- 编辑模式按钮 -->
      <template v-if="pageMode === 'edit' || pageMode === 'add'">
        <el-button 
          type="primary" 
          @click="submitForm"
          :loading="submitLoading"
          :disabled="submitLoading"
        >确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </template>

      <!-- 详情模式按钮 -->
      <template v-if="pageMode === 'detail'">
        <el-button @click="handleCancel">关 闭</el-button>
      </template>

      <!-- 审批模式按钮 -->
      <template v-if="pageMode === 'approve'">
        <el-button 
          type="success" 
          @click="handleApprovePass"
          :loading="approvePassLoading"
          :disabled="approvePassLoading"
        >通 过</el-button>
        <el-button 
          type="danger" 
          @click="handleApproveReject"
          :loading="approveRejectLoading"
          :disabled="approveRejectLoading"
        >驳 回</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </template>
    </div>
  </div>
</template>

<script setup name="UniversityMentorEdit">
import {
  addItem,
  editItem,
  getDetail,
} from "@/api/university-mentor";
import { getStudentList, getTeacherList } from "@/api/common";
import { handleApproval } from "@/api/approval";
import useUserStore from "@/store/modules/user";
import { selectDictLabel } from "@/utils/ruoyi";
import { isPhone } from "@/utils/index";
import ApprovalProgress from "@/components/ApprovalProgress";

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const { professional_title, educational_qualifications } = proxy.useDict("professional_title", "educational_qualifications");

// 页面模式: add(新增) | edit(编辑) | detail(详情) | approve(审批)
const pageMode = ref('add');
const formRef = ref();
const submitLoading = ref(false);
const approvePassLoading = ref(false);
const approveRejectLoading = ref(false);

const form = reactive({
  id: undefined,
  userId: useUserStore().id,
  schoolTeacherUserId: undefined,
  approvalRemark: undefined,
  approvalStatus: undefined,
  approvalInfoId: undefined,
  approvalNodeId: undefined,
});

const rules = {
  schoolTeacherUserId: [
    { required: true, message: "请选择高校导师", trigger: "change" },
  ],
};

const userList = ref([]);
const schoolTeacherUserList = ref([]);
const selectedSchoolTeacher = ref(null);

// 初始化页面
onMounted(() => {
  // 获取学生列表
  getStudentList({ roleKey: "student" }).then((res) => {
    userList.value = res.data;
  });

  // 根据路由参数判断页面模式
  const { mode, id } = route.query;
  pageMode.value = mode || 'add';

  if (id && id !== 'new') {
    // 加载数据
    getDetail(id).then((response) => {
      Object.assign(form, response.data);
      handleStudentChange(response.data.userId);
    });
  } else if (pageMode.value === 'add') {
    // 新增模式，使用当前用户
    form.userId = useUserStore().id;
    handleStudentChange(useUserStore().id);
  }
});

/** 学生选择变更 */
function handleStudentChange(userId) {
  if (!userId) return;
  getTeacherList({ userId: userId, roleKey: "school_teacher" }).then(
    (res) => {
      schoolTeacherUserList.value = res.data;
      // 如果表单中已有高校导师ID，设置选中的高校导师信息
      if (form.schoolTeacherUserId) {
        setTimeout(() => {
          handleSchoolTeacherChange(form.schoolTeacherUserId);
        }, 50);
      }
    }
  );
}

/** 高校导师选择变更 */
function handleSchoolTeacherChange(userId) {
  if (userId) {
    selectedSchoolTeacher.value =
      schoolTeacherUserList.value.find(
        (teacher) => teacher.userId === userId
      ) || null;
  } else {
    selectedSchoolTeacher.value = null;
  }
}

/** 提交表单 */
function submitForm() {
  if (submitLoading.value) return;
  
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      
      if (form.id != undefined) {
        editItem(form).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          router.back();
        }).catch((error) => {
          console.error("修改失败:", error);
        }).finally(() => {
          submitLoading.value = false;
        });
      } else {
        addItem(form).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          router.back();
        }).catch((error) => {
          console.error("新增失败:", error);
        }).finally(() => {
          submitLoading.value = false;
        });
      }
    }
  });
}

/** 审批通过 */
function handleApprovePass() {
  if (approvePassLoading.value) return;
  
  approvePassLoading.value = true;
  const approvalData = {
    approvalInfoId: form.approvalInfoId,
    approvalNodeId: form.approvalNodeId,
    approvalStatus: "approved",
    remark: form.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("审批通过");
    router.back();
  }).catch((error) => {
    console.error("审批通过失败:", error);
  }).finally(() => {
    approvePassLoading.value = false;
  });
}

/** 审批驳回 */
function handleApproveReject() {
  if (!form.approvalRemark) {
    proxy.$modal.msgError("请填写审核意见");
    return;
  }

  if (approveRejectLoading.value) return;
  
  approveRejectLoading.value = true;
  const approvalData = {
    approvalInfoId: form.approvalInfoId,
    approvalNodeId: form.approvalNodeId,
    approvalStatus: "rejected",
    remark: form.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("已驳回");
    router.back();
  }).catch((error) => {
    console.error("审批驳回失败:", error);
  }).finally(() => {
    approveRejectLoading.value = false;
  });
}

/** 取消 */
function handleCancel() {
  router.back();
}
</script>

<style scoped>
.dialog-footer {
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>
